import random

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from users.serializers import UserSerializer
from verifications import constants

# 获取日志器
import logging

logger=logging.getLogger('django')



# GET /sms_codes/(?P<mobile>1[3-9]\d{9})/
class SMSCodeView(APIView):
    def get(self,request,mobile):
        """
        获取短信验证码:
        1. 随机生成6位数字作为短信验证码
        2. 在redis中存储短信验证码内容，以`mobile`为key，以短信验证码的内容为value
        3. 使用云通讯给`mobile`发送短信验证码
        4. 返回应答，发送短信成功
        """
        # 获取短信验证码:
        #2.2获取mobile发送短信标记
        redis_conn=get_redis_connection('verify_codes_hss')   #根据redis空间名:verify_codes_hss可以获取对应存储空间的链接地址
        send_flag=redis_conn.get('send_flag_%s'%mobile)
        if send_flag:
            return Response({'message':'发送过于频繁'},status=status.HTTP_400_BAD_REQUEST)



        # 1. 随机生成6位数字作为短信验证码
        sms_code='%06d'%random.randint(0,999999)
        print(sms_code)

        # 2. 在redis中存储短信验证码内容，以`mobile`为key，以短信验证码的内容为value
        # redis_conn=get_redis_connection('verify_codes_hss')   #根据redis空间名:verify_codes_hss可以获取对应存储空间的链接地址
        # redis_conn.setex('<key>','<expires>','<value>')
        pl = redis_conn.pipeline()
        pl.setex('sms_%s'%mobile,constants.SMS_CODE_REDIS_EXPIRES,sms_code)
        pl.setex('send_flag_%s'%mobile,constants.SEND_SMS_CODE_INTERVAL,1)
        # print('constants的打印',constants.SEND_SMS_CODE_INTERVAL)
        pl.execute()

        # 3. 使用云通讯给`mobile`发送短信验证码
        expires=constants.SMS_CODE_REDIS_EXPIRES//60

        #发出发送短信的任务消息
        from celery_tasks.sms.tasks import send_sms_code_33
        send_sms_code_33.delay(mobile,sms_code,expires)
        # try:
        #     res=CCP().send_template_sms(mobile,[sms_code,expires],constants.SMS_CODE_TEMP_ID)
        # except Exception as e:
        #     logger.error(e)
        #     return Response({'message':'发送短信异常'},status=status.HTTP_503_SERVICE_UNAVAILABLE)
        # if res !=0:
        #     return Response({'message':'发送短信失败'},status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 4. 返回应答，发送短信成功
        return Response({'message': '发送短信成功'})


